import axios from "axios";
import router from "@/router";

const request = axios.create({
    baseURL: 'http://localhost:9001',
    timout: 3000
})

/**
 * request拦截器
 * 发送request请求前做一些处理
 * 例如统一加token
 */
request.interceptors.request.use(config => {
    config.headers['Context-Type'] = 'application/json;charset=utf-8';
    return config
}, error => {
    return Promise.reject(error)
});

/**
 * response 拦截器
 * 在接口响应后统一处理结果
 */
request.interceptors.response.use(response => {
        let res = response.data;
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        if (res.code === '401') {
            router.push('/login')
        }
        return res;
    },
    error => {
        console.log('error' + error)
        return Promise.reject(error)
    }
)

export default request